﻿using System;
using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System.Web.Configuration;

namespace ScrumFactory.Services.Web.Setup {
    public partial class _default : System.Web.UI.Page {

        protected void Page_Load(object sender, EventArgs e) {

        }

        protected void createDb_Click(object sender, EventArgs e) {

            DB_CREATE_ERR_MESSAGE = null;
            bool dbOk = CreateDB();

            if (dbOk)
                DB_Sucess();

        }

        private void DB_Sucess() {           
            Response.Redirect("~/default.aspx");

        }

        private string ConnectionString {
            get {
                return String.Format("Data Source={0};User ID={1};Password={2}", serverTextBox.Text, userTextBox.Text, passTextBox.Text);
            }
        }

        public string DB_CREATE_ERR_MESSAGE {
            set {
                DB_CREATE_ERR_MESSAGE_LIT.Text = value;
                if(string.IsNullOrEmpty(value))
                    DB_CREATE_ERR_MESSAGE_LIT.Visible = false;
                else
                    DB_CREATE_ERR_MESSAGE_LIT.Visible = true;
            }
        }

        private bool CreateDB() {
            
            try {                
                string dbScriptPath = Server.MapPath("~/App_Data/DB_SCRIPT/DB_SCRIPT.sql");
                FileInfo fileInfo = new FileInfo(dbScriptPath);
                string script = fileInfo.OpenText().ReadToEnd();                
                SqlConnection connection = new SqlConnection(ConnectionString);
                Server server = new Server(new ServerConnection(connection));
                int r = server.ConnectionContext.ExecuteNonQuery(script);
            }
            catch (System.Exception ex) {
                string msg = ex.Message;
                if (ex.InnerException != null)
                    msg = msg + "</br>" + ex.InnerException.Message;

                DB_CREATE_ERR_MESSAGE = msg;
                

                return false;
            }
            return true;
        }
    }
}